LOADING...

loading

Json.stringify九个特征

特性一

undefined、任意的函数以及symbol值,出现在非数组对象的属性值中时在序列化过程中会被忽略
undefined、任意的函数以及symbol值出现在数组中时会被转换成 null
undefined、任意的函数以及symbol值被单独转换时,会返回 undefined

// 1. 对象中存在这三种值会被忽略
console.log(JSON.stringify({
  name: 'Gregory',
  sex: 'boy',
  // 函数会被忽略
  showName () {
    console.log('Gregory')
  },
  // undefined会被忽略
  age: undefined,
  // Symbol会被忽略
  symbolName: Symbol('Gregory')
}))
// '{"name":"Gregory","sex":"boy"}'

// 2. 数组中存在着三种值会被转化为null
console.log(JSON.stringify([
  'Gregory',
  'boy',
  // 函数会被转化为null
  function showName () {
    console.log('Gregory')
  },
  //undefined会被转化为null
  undefined,
  //Symbol会被转化为null
  Symbol('Gregory')
]))
// '["Gregory","boy",null,null,null]'
 
// 3.单独转换会返回undefined
console.log(JSON.stringify(
  function showName () {
    console.log('Gregory')
  }
)) // undefined
console.log(JSON.stringify(undefined)) // undefined
console.log(JSON.stringify(Symbol('Gregory'))) // undefined

特性二

布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值

console.log(JSON.stringify([new Number(1), new String("Gregory"), new Boolean(false)]))
// '[1,"Gregory",false]'

特性三

所有以symbol为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。

console.log(JSON.stringify({
  name: Symbol('Gregory'),
}))
// '{}'
console.log(JSON.stringify({
  [ Symbol('Gregory') ]: 'Gregory',
}, (key, value) => {
  if (typeof key === 'symbol') {
    return value
  }
}))
// undefined

特性四

NaNInfinity 格式的数值及 null 都会被当做 null

console.log(JSON.stringify({
  age: NaN,
  age2: Infinity,
  name: null
}))
// '{"age":null,"age2":null,"name":null}'

特性五

转换值如果有 toJSON() 方法,该方法定义什么值将被序列化。

const toJSONObj = {
  name: 'Gregory',
  toJSON () {
    return 'JSON.stringify'
  }
}
 
console.log(JSON.stringify(toJSONObj))
// "JSON.stringify"

特性六

Date 日期调用了 toJSON() 将其转换为了 string 字符串(同Date.toISOString()),因此会被当做字符串处理。

const d = new Date()
 
console.log(d.toJSON()) // 2021-10-05T14:01:23.932Z
console.log(JSON.stringify(d)) // "2021-10-05T14:01:23.932Z"

特性七

对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误。

let cyclicObj = {
  name: 'Gregory',
}
 
cyclicObj.obj = cyclicObj
 
console.log(JSON.stringify(cyclicObj))
// Converting circular structure to JSON

特性八

其他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性

let enumerableObj = {}
 
Object.defineProperties(enumerableObj, {
  name: {
    value: 'Gregory',
    enumerable: true
  },
  sex: {
    value: 'boy',
    enumerable: false
  },
})
 
console.log(JSON.stringify(enumerableObj))
// '{"name":"Gregory"}'

特性九

当尝试去转换 BigInt 类型的值会抛出错误

const alsoHuge = BigInt(9007199254740991)
 
console.log(JSON.stringify(alsoHuge))
// TypeError: Do not know how to serialize a BigInt